/***************************************************************************
 *   Copyright (C) 2009 - 2010 by Simon Qian <SimonQian@SimonQian.com>     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "vsf.h"
#include "usrapp.h"

struct usrapp_t usrapp =
{
	.debug.stream_tx.op = &stdout_stream_op,
	.debug.stream_rx.op = &stdin_stream_op,
};

void usrapp_srt_init(struct usrapp_t *app)
{
	int argc = app->argc;
	char **argv = app->argv;

	VSFSTREAM_INIT(&app->debug.stream_rx);
	VSFSTREAM_INIT(&app->debug.stream_tx);
	vsfdbg_init((struct vsf_stream_t *)&app->debug.stream_tx);

	if (argc < 2)
	{
		vsfdbg_prints("need rom" VSFCFG_DEBUG_LINEEND);
		return;
	}

	FILE *rom = fopen(argv[1], "rb");
	if (!rom)
	{
		vsfdbg_printf("fail to open rom %s" VSFCFG_DEBUG_LINEEND, argv[1]);
		return;
	}
	
	fseek(rom, 0, SEEK_END);
	uint32_t size = ftell(rom);
	fseek(rom, 0, SEEK_SET);
	app->rom = vsf_bufmgr_malloc(size);
	if (!app->rom)
	{
		vsfdbg_prints("fail to allocate buffer for rom" VSFCFG_DEBUG_LINEEND);
		return;
	}

	if (fread(app->rom, 1, size, rom) != size)
	{
		vsfdbg_printf("fail to read rom %s" VSFCFG_DEBUG_LINEEND, argv[1]);
		fclose(rom);
		return;
	}
	fclose(rom);

	app->jeg.nes.rom.buffer = app->rom;
	app->jeg.nes.rom.size = size;
	vsfjeg_init(&app->jeg);
}

void usrapp_srt_poll(struct usrapp_t *app){}

void usrapp_nrt_init(struct usrapp_t *app){}

void usrapp_nrt_poll(struct usrapp_t *app)
{
	vsfjeg_poll(&app->jeg);
}

bool usrapp_cansleep(struct usrapp_t *app)
{
	return false;
}

void usrapp_initial_init(struct usrapp_t *app){}
